/********************************************************************************
 *    Copyright (C) 2014 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH    *
 *                                                                              *
 *              This software is distributed under the terms of the             *
 *              GNU Lesser General Public Licence (LGPL) version 3,             *
 *                  copied verbatim in the file "LICENSE"                       *
 ********************************************************************************/
#include "HiMusicMappedData.h"
#include "HiMusicWaveForm.h"
#include "TString.h"
#include "TCanvas.h"
#include "TGraph.h"
#include "TROOT.h"
#include <iostream>

HiMusicMappedData::HiMusicMappedData() : fEventID(0),
                                         fDetID(0),
                                         fNChannel(0),
                                         fTimeSliceID(0)
{
    fChanData = new TClonesArray("HiMusicWaveForm", 10);
}

HiMusicMappedData::HiMusicMappedData(uint64_t eventID,
                                     uint8_t detID,
                                     uint8_t nChannel,
                                     uint64_t timeSliceID)
    : fEventID(eventID),
      fDetID(detID),
      fNChannel(nChannel),
      fTimeSliceID(timeSliceID)
{
    fChanData = new TClonesArray("HiMusicWaveForm", 10);
}

HiMusicMappedData::HiMusicMappedData(const HiMusicMappedData &data)
    : TObject(data),
      fEventID(data.fEventID),
      fDetID(data.fDetID),
      fNChannel(data.fNChannel),
      fTimeSliceID(data.fTimeSliceID)
{
    fChanData = new TClonesArray("HiMusicWaveForm", 10);
    for (int i = 0; i < data.fChanData->GetEntriesFast(); ++i)
    {
        HiMusicWaveForm *srcChan = (HiMusicWaveForm *)data.fChanData->At(i);
        new ((*fChanData)[i]) HiMusicWaveForm(*srcChan);
    }
}

HiMusicMappedData::~HiMusicMappedData()
{
    fChanData->Clear();
    delete fChanData;
}

void HiMusicMappedData::Reset()
{
    fEventID = 0;
    fDetID = 0;
    fNChannel = 0;
    fTimeSliceID = 0;
    fChanData->Clear();
}

void HiMusicMappedData::Plot(Int_t n)
{
    if (n < 0 || n >= fNChannel)
    {
        std::cout << "Channel index out of range!" << std::endl;
        return;
    }
    HiMusicWaveForm *waveform = (HiMusicWaveForm *)fChanData->At(n);
    if (waveform)
    {
        TString title = Form("Channel: %d", n);
        TCanvas *can = (TCanvas *)gROOT->FindObject("HiMusicPlotWave");
        if (!can)
        {
            can = new TCanvas("HiMusicPlotWave", "HiMusicPlotWave", 800, 600);
        }
        waveform->Plot();
    }
    else
    {
        std::cout << "No waveform data for channel " << n << "!" << std::endl;
    }
}

ClassImp(HiMusicMappedData);